# myapp/serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.exceptions import ValidationError

class ResetPasswordSerializer(serializers.Serializer):
    new_password = serializers.CharField(required=True)

class ForgotPasswordSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)

class UpdatePasswordSerializer(serializers.Serializer):
    current_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True, min_length=8)

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'email', 'password']
        extra_kwargs = {
            'password': {'write_only': True}  # 确保密码不会被返回
        }

    def validate(self, data):
        # 检查用户名是否已存在
        if User.objects.filter(username=data.get('username')).exists():
            raise ValidationError({'username': ['This username is already in use.']})

        # 检查电子邮件是否已存在
        if User.objects.filter(email=data.get('email')).exists():
            raise ValidationError({'email': ['This email is already in use.']})

        return data

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            password=validated_data['password']
        )
        return user